﻿using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Fabrikam.Phone.Resources;
using Fabrikam.Phone.DataModel;
using Microsoft.Phone.Controls;

namespace Fabrikam.Phone.ViewModels
{
    public class MainViewModel : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;
        public RelayCommand SaveCommand { get; set; }
        public RelayCommand RefreshCommand { get; set; }
        public RelayCommand SyncCommand { get; set; }
        public RelayCommand NextCommand { get; set; }
        public RelayCommand PreviousCommand { get; set; }

        private void RaisePropertyChanged(string propertyName)
        {
            if (this.PropertyChanged != null)
                this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }

        public const string IsLoadingPropertyName = "IsLoading";

        private bool isLoading;

        /// <summary>
        /// Sets and gets the IsLoading property.
        /// Changes to that property's value raise the PropertyChanged event. 
        /// </summary>
        public bool IsLoading
        {
            get
            {
                return isLoading;
            }

            set
            {
                if (isLoading == value)
                    return;

                isLoading = value;
                RaisePropertyChanged(IsLoadingPropertyName);
            }
        }

     
        public const string ServiceTicketsPropertyName = "ServiceTickets";

        private ObservableCollection<ServiceTicketViewModel> serviceTickets = new ObservableCollection<ServiceTicketViewModel>();

        public ObservableCollection<ServiceTicketViewModel> ServiceTickets
        {
            get
            {
                return serviceTickets;
            }

            set
            {
                if (serviceTickets == value)
                {
                    return;
                }

                serviceTickets = value;
                RaisePropertyChanged(ServiceTicketsPropertyName);
            }
        }


        public const string CurrentServiceTicketPropertyName = "CurrentServiceTicket";

        private ServiceTicketViewModel currentServiceTicket;

        public ServiceTicketViewModel CurrentServiceTicket
        {
            get
            {
                return currentServiceTicket;
            }

            set
            {
                if (currentServiceTicket == value)
                {
                    return;
                }

                currentServiceTicket = value;
                RaisePropertyChanged(CurrentServiceTicketPropertyName);
            }
        }
        public MainViewModel()
        {
     
            this.RefreshCommand = new RelayCommand(async () => await Refresh());
            this.SaveCommand = new RelayCommand(async () => await Save());
            this.SyncCommand = new RelayCommand(async () => await Sync());

  
        }

      
        /// <summary>
        /// Sample property that returns a localized string
        /// </summary>
        public string LocalizedSampleProperty
        {
            get
            {
                return AppResources.SampleProperty;
            }
        }

        private async Task Save()
        {
          //  await DataService.Current.UpdateServiceTickets(this.ServiceTickets);
        }

        private async Task Sync()
        {
            try
            {
                this.IsLoading = true;
                var result = await DataService.Current.Sync();


                CustomMessageBox messageBox = new CustomMessageBox()
                {
                    Caption = "Synchronization",
                    Message = "Synchronization done." + Environment.NewLine + 
                              "Downloaded changes : " + result.TotalDownloads + "." + Environment.NewLine + 
                              "Uploaded changes : " + result.TotalUploads + "." + Environment.NewLine + 
                              "Conflicts : " + result.TotalSyncConflicts + "." + Environment.NewLine + 
                              "Duration : " + result.EndTime.Subtract(result.StartTime).TotalSeconds + " sec."
                              ,
                    LeftButtonContent = "Ok",
                    IsFullScreen = false
                };

                this.IsLoading = false;

                messageBox.Show(); 

                await Refresh();
            }
            catch (Exception e)
            {
                Debug.WriteLine(e.Message);
                throw;
            }
        }

        private async Task Refresh()
        {
            return;

            try
            {
                var tableExist = DataService.Current.TableExist("ServiceTickets");

                if (!tableExist)
                    return;

                this.ServiceTickets.Clear();

                var customers = await DataService.Current.GetCustomers();
                var tickets = await DataService.Current.GetTickets();

                foreach (var t in tickets)
                {
                    var c = customers.FirstOrDefault(cust => cust.ID == t.CustomerID);
                    ServiceTicketViewModel serviceTicketViewModel = new ServiceTicketViewModel(t, c, customers);
                    this.ServiceTickets.Add(serviceTicketViewModel);
                }


            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }
        }

    }
}